// 管理用户收藏云函数（添加/取消收藏）
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, type, itemId } = event
  
  try {
    console.log('管理用户收藏，操作:', action, '类型:', type, '项目ID:', itemId)
    
    // 直接使用openid作为用户标识
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }
    
    const userOpenid = wxContext.OPENID

    if (!action || !type || !itemId) {
      return {
        success: false,
        message: '参数不完整',
        error: 'MISSING_PARAMS'
      }
    }

    if (!['add', 'remove'].includes(action)) {
      return {
        success: false,
        message: '操作类型无效',
        error: 'INVALID_ACTION'
      }
    }

    if (!['activity', 'goods'].includes(type)) {
      return {
        success: false,
        message: '收藏类型无效',
        error: 'INVALID_TYPE'
      }
    }

    // 查询用户收藏记录
    const collectionResult = await db.collection('user_collection')
      .where({
        userId: userOpenid
      })
      .get()

    let userCollection
    let isNewRecord = false

    if (collectionResult.data.length === 0) {
      // 用户还没有收藏记录，创建新记录
      userCollection = {
        userId: userOpenid,
        activityLikes: [],
        goodsLikes: [],
        createdAt: new Date(),
        updatedAt: new Date()
      }
      isNewRecord = true
    } else {
      userCollection = collectionResult.data[0]
    }

    // 根据类型确定要操作的字段
    const fieldName = type === 'activity' ? 'activityLikes' : 'goodsLikes'
    let currentList = userCollection[fieldName] || []

    // 执行添加或删除操作
    if (action === 'add') {
      // 添加收藏
      if (!currentList.includes(itemId)) {
        currentList.push(itemId)
        console.log(`添加${type}收藏:`, itemId)
      } else {
        return {
          success: false,
          message: '已经收藏过了',
          error: 'ALREADY_COLLECTED'
        }
      }
    } else if (action === 'remove') {
      // 取消收藏
      const index = currentList.indexOf(itemId)
      if (index > -1) {
        currentList.splice(index, 1)
        console.log(`取消${type}收藏:`, itemId)
      } else {
        return {
          success: false,
          message: '未找到收藏记录',
          error: 'NOT_FOUND'
        }
      }
    }

    // 更新数据库
    userCollection[fieldName] = currentList
    userCollection.updatedAt = new Date()

    let updateResult
    if (isNewRecord) {
      // 创建新记录
      updateResult = await db.collection('user_collection').add({
        data: userCollection
      })
      console.log('创建新的收藏记录:', updateResult)
    } else {
      // 更新现有记录
      updateResult = await db.collection('user_collection')
        .doc(userCollection._id)
        .update({
          data: {
            [fieldName]: currentList,
            updatedAt: new Date()
          }
        })
      console.log('更新收藏记录:', updateResult)
    }

    const actionText = action === 'add' ? '收藏' : '取消收藏'
    const typeText = type === 'activity' ? '活动' : '商品'

    return {
      success: true,
      data: {
        action,
        type,
        itemId,
        currentCount: currentList.length
      },
      message: `${actionText}${typeText}成功`
    }

  } catch (error) {
    console.error('管理用户收藏失败:', error)
    return {
      success: false,
      message: '操作失败',
      error: error.message,
      details: error
    }
  }
}